var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var webim = global.webim;
var webimhandler = global.webimhandler;
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    list: [],
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    total: 0,
    isBottom: false,
    nickName: "",
    pickerArr: ["扫码","分享", "搜索", "交接"],
    selSource: "",
    relationMap: {},

    tabActive: "customer",

    loadingCus: false,
    groupList: [],
    customerByGroup: {}, //缓存数据
    customerRelationByGroup: {} //缓存数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    var that = this;
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      that.findByEmployeeOpenId();
      that.findGroupList();
    });
  },
  gotoDetail: function (e) {
    var mid = e.currentTarget.dataset.mid;
    var src = e.currentTarget.dataset.src;
    var openid = e.currentTarget.dataset.openid;
    var eId = e.currentTarget.dataset.eid;
    let employee = wx.getStorageSync('employee')
     //收集点击名片海报信息
     app.globalData.sensors.track('1010', {
      account_id: wx.getStorageSync('userId'),
      role: employee ? '置业顾问' : '用户'
    });
    wx.navigateTo({
      url: "/pages/sales/custom_detail/index?" + "&openid=" + openid + "&src=" + src + "&eId=" + eId,
    });

  },
  bindPickerChange(e) {
    let ctx = this;
    let sType = this.data.pickerArr[e.detail.value].key;
    let name = this.data.pickerArr[Number(e.detail.value)];
    ctx.setData({
      selSource: sType,
      pickerName: name,
      curPage: 0,
      isBottom: false,
      list: []
    });
    ctx.findByEmployeeOpenId();
  },
  
  findByEmployeeOpenId() {
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    ctx.setData({
      isLoading: true
    });
    wx.request({
      //url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/findByEmployeeOpenId",
      url:`${cf.config.pageDomain}applet/mobile/visitcard/memberrelation/findByEmployeeName`,
      data: {
        cusmallToken: cusmallToken,
        nickName: ctx.data.nickName,
        start: ctx.data.curPage,
        limit: ctx.data.pageSize,
        source: ctx.data.selSource
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          console.log('////////////............',data.model.relation)
          if (data.model.relation) {
            data.model.relation = data.model.relation.filter(item=>item)
            for (let item of data.model.relation) {
              item.followSatus = (item.followTime && ctx.followTimeToTxt(item.followTime)) || "未跟进客户";
              ctx.setData({
                ['relationMap.' + item.memberId + '']: item

              });
            }
          } else {
            ctx.setData({
              relationMap: null
            })
          }

          var list = data.model.list || [];
          list = list.filter((item,index)=>{
            if(item){
              item.source = data.model.relation[index].source
            }
            return item
          })
          console.log('///////////////////',list)
          for (let item of list) {
            if(item){
              if (ctx.data.selSource==4){
                item.behaviorTime = util.formatTime(new Date(ctx.data.relationMap[item.id].lastBrowserTime || ctx.data.relationMap[item.id].createTime));
              }else{
                item.behaviorTime = util.formatTime(new Date(ctx.data.relationMap[item.id].createTime));
              }
              item.sourceTimeTxt = ctx.getSource(item.source);
            }
          }
          
          console.log('///////////////',list)
          ctx.setData({
            list: ctx.data.list.concat(list),
            total: data.model.total
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }

        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({
          isLoading: false
        });
      }
    });
  },
  getSource(src) {
    switch (src) {
      case 0:
        return "最后扫描";
      case 1:
        return "最后分享";
      case 2:
        return "最后搜索";
      case 3:
        return "最后交接";
      default:
        return "";
    }
  },

  changeInput(e) {
    var ctx = this;
    var str = e.detail.value;
    ctx.setData({
      nickName: str
    });
  },
  resetSearch() {
    var ctx = this;
    ctx.setData({
      list: [],
      isLoading: false,
      pageSize: 10,
      curPage: 1,
      isBottom: false,
      tabActive: "customer"
    });
    ctx.findByEmployeeOpenId();
  },
  changeTab(e) {
    let ctx = this;
    let name = e.currentTarget.dataset.name;
    ctx.setData({
      tabActive: name
    });
  },
  addGroup() {
    wx.navigateTo({
      url: './add_group',
    });
  },
  manageGroup() {
    wx.navigateTo({
      url: './manage_group',
    });
  },
  findGroupList() {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/relationgroup/findList",
      data: {
        cusmallToken: cusmallToken,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          let list = data.model.list.filter(item=>item);
          let customerByGroup = {};
          let customerRelationByGroup = {};
          for (let item of list) {
            customerByGroup[item.id] = [];
            customerRelationByGroup[item.id] = {};
            item.expand = false;
          }
          ctx.setData({
            groupList: data.model.list.filter(item=>item),
            customerByGroup: customerByGroup,
            customerRelationByGroup: customerRelationByGroup
          });
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({
          isLoading: false
        });
      }
    });
  },

  getGroupCustomer(e) {
    var ctx = this;
    let groupId = e.currentTarget.dataset.gid;
    let idx = e.currentTarget.dataset.idx;
    ctx.setData({
      ["groupList[" + idx + "].expand"]: !ctx.data.groupList[idx].expand
    });
    if (0 < ctx.data.customerByGroup[groupId].length || ctx.data.loadingCus) {
      return;
    }
    ctx.setData({
      loadingCus: true
    });
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/relationgroup/findGroupMemberList",
      data: {
        cusmallToken: cusmallToken,
        groupId: groupId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        wx.hideLoading();
        if (data && 0 === data.ret) {
          if (data.model.relation) {
            var relationMap = {};
            for (let item of data.model.relation) {
              item.followSatus = (item.followTime && ctx.followTimeToTxt(item.followTime)) || "未跟进客户";
              relationMap[item.memberId] = item;
            }

          }

          var list = data.model.list || [];
          list = list.filter((item,index)=>{
            if(item){
              item.source = data.model.relation[index].source
            }
            return item
          })
          for (let item of list) {
            item.behaviorTime = util.formatTime(new Date(relationMap[item.id].createTime));
            item.sourceTimeTxt = ctx.getSource(item.source);

          }

          ctx.setData({
            ["customerByGroup." + groupId + ""]: list,
            ["customerRelationByGroup." + groupId + ""]: relationMap,
          });

        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          });
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({
          loadingCus: false
        });
      }
    });
  },
  handleRefreshData() {
    let ctx = this;
    ctx.setData({
      loadingCus: false,
      groupList: [],
      customerByGroup: {}, //缓存数据
      customerRelationByGroup: {}, //缓存数据
    });

    ctx.findGroupList();
  },
  //删除变更的信息
  delCustomer(e) {
    var id = e.currentTarget.dataset.customerid;
    var index = e.currentTarget.dataset.itemindex;
    var ctx = this;
    wx.showModal({
      title: '提示',
      content: '你确定要删除吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/deleteAfterChange",
            data: {
              cusmallToken: cusmallToken,
              id: id
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              var data = res.data;
              if (data && 0 == data.ret) {
                ctx.data.list.splice(index, 1);
                ctx.setData({
                  list: ctx.data.list
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.handleRefreshData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let ctx = this;
    ctx.setData({
      curPage: 1,
      list: [],
      total: 0,
      isBottom: false,
      loadingCus: false,
      groupList: [],
      customerByGroup: {}, //缓存数据
      customerRelationByGroup: {}, //缓存数据
    });

    ctx.findGroupList();
    ctx.findByEmployeeOpenId();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let ctx = this;
    if (ctx.data.isLoading) {
      return;
    }
    ctx.setData({
      curPage: ctx.data.curPage + 1
    });
    ctx.findByEmployeeOpenId();
  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))